package tmt.usercenter.web.configure.fileservice;

import com.tmt.fileservice.IFileCache;
import com.tmt.fileservice.IFileService;
import com.tmt.fileservice.IFileStorage;
import com.tmt.fileservice.IFileValidator;
import com.tmt.fileservice.impl.DefaultFileDispatcher;
import com.tmt.fileservice.impl.DefaultFileService;
import com.tmt.fileservice.impl.DefaultFileStorage;
import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import tmt.usercenter.web.configure.IgniteConfig;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ThreeManTeam on 2017/5/20.
 */
@Configuration
@AutoConfigureAfter(IgniteConfig.class)
@ConditionalOnProperty(name={"fileservice.enabled"}, havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(FileServiceProperties.class)
public class FileServiceConfig {

    @Autowired
    private FileServiceProperties fServiceProperties;

    @Value("${fileservice.protocol:http}")
    private String serverProtocol;

    @Value("${fileservice.address:localhost}")
    private String serverAddress;

    @Value("${fileservice.port}")
    private int serverPort;

    @Value("${server.context-path}")
    private String serverContextPath;

    /**
     * 引入这个Bean主要作用是：保证在配置FileService Bean之前Ignite Bean已经被加载了
     */
    @Autowired(required = false)
    private Ignite igniteInstance;

    private final Logger logger = LoggerFactory.getLogger(FileServiceConfig.class);

    @Bean
    @ConditionalOnClass({DefaultFileService.class})
    public IFileService fileService() {

        FileDispatcherProperties fdp = fServiceProperties.getFdProperties();
        DefaultFileDispatcher fileDispatcher = DefaultFileDispatcher.getInstance(
                serverProtocol, serverAddress, serverPort,
                serverContextPath, fdp.getBaseUrl(),fdp.getBaseDir(),
                fdp.getMainDir(), fdp.getTmpDir(), fdp.getFileExpiredTime());

        FileStorageProperties fsp = fServiceProperties.getFsProperties();

        Map<String, IFileValidator> fileValidatorMap = new HashMap<>();
        fsp.getValidators().keySet().stream().forEach(x->{
            FileValidatorProperties validatorConfig = fsp.getValidators().get(x);
            String clsName = validatorConfig.getClassName();
            try {
                IFileValidator ifs = (IFileValidator) Class.forName(clsName).newInstance();
                ifs.setParams(validatorConfig.getParams());
                fileValidatorMap.put(x, ifs);
            }catch (Exception ex){
                logger.debug(MessageFormat.format("------文件效验器类加载异常:{0}-{1}-----", x, clsName));
            }
        });

        IFileCache ifc = null;
        FileCacheProperties fcp = fsp.getCache();
        try {
            if (fcp != null && fcp.isEnabled()) {
                ifc = (IFileCache) Class.forName(fcp.getClassName()).newInstance();
                ifc.setConfig(fcp.getParams());
            }
        } catch (Exception ex) {
            logger.debug(MessageFormat.format("------文件缓存类加载异常:{0}-----", fcp.getClassName()));
        }

        IFileStorage fileStorage = DefaultFileStorage.getInstance(fileValidatorMap);
        fileStorage.setFileCache(ifc);

        return DefaultFileService.createInstance(fileDispatcher, fileStorage);

    }

}
